#include "service/chat/chat_service.h"
#include "common/logger/logger.h"
#include <sstream>
#include <iomanip>
#include <ctime>

using namespace common::logger;

namespace service {
    namespace chat {

// 消息转换为JSON
        nlohmann::json ChatMessage::toJson() const {
            nlohmann::json json;
            json["id"] = id;
            json["sender_id"] = senderId;
            json["receiver_id"] = receiverId;
            json["content"] = content;
            json["created_at"] = createdAt;
            json["type"] = type;
            json["status"] = status;
            return json;
        }

// 从JSON构造消息
        ChatMessage ChatMessage::fromJson(const nlohmann::json& json) {
            ChatMessage message;
            message.id = json.value("id", 0);
            message.senderId = json.value("sender_id", 0);
            message.receiverId = json.value("receiver_id", 0);
            message.content = json.value("content", "");
            message.createdAt = json.value("created_at", "");
            message.type = json.value("type", 0);
            message.status = json.value("status", 0);
            return message;
        }

// 聊天室转换为JSON
        nlohmann::json ChatRoom::toJson() const {
            nlohmann::json json;
            json["id"] = id;
            json["name"] = name;
            json["description"] = description;
            json["creator_id"] = creatorId;
            json["created_at"] = createdAt;
            json["type"] = type;
            return json;
        }

// 从JSON构造聊天室
        ChatRoom ChatRoom::fromJson(const nlohmann::json& json) {
            ChatRoom room;
            room.id = json.value("id", 0);
            room.name = json.value("name", "");
            room.description = json.value("description", "");
            room.creatorId = json.value("creator_id", 0);
            room.createdAt = json.value("created_at", "");
            room.type = json.value("type", 0);
            return room;
        }

// 创建聊天服务实例
        std::shared_ptr<ChatService> ChatService::create(
                std::shared_ptr<database::MySQLPool> dbPool,
                std::shared_ptr<cache::RedisClient> redisClient,
                std::shared_ptr<messaging::KafkaProducer> kafkaProducer,
                std::shared_ptr<messaging::KafkaConsumer> kafkaConsumer) {
            return std::shared_ptr<ChatService>(new ChatService(dbPool, redisClient, kafkaProducer, kafkaConsumer));
        }

// 构造函数
        ChatService::ChatService(std::shared_ptr<database::MySQLPool> dbPool,
                                 std::shared_ptr<cache::RedisClient> redisClient,
                                 std::shared_ptr<messaging::KafkaProducer> kafkaProducer,
                                 std::shared_ptr<messaging::KafkaConsumer> kafkaConsumer)
                : dbPool_(dbPool), redisClient_(redisClient), kafkaProducer_(kafkaProducer), kafkaConsumer_(kafkaConsumer), isRunning_(false) {
        }

// 启动服务
        bool ChatService::start(int port) {
            if (isRunning_) {
                return false;
            }

            // 创建EpollServer
            server_ = std::make_unique<network::EpollServer>(port);

            // 设置回调函数
            server_->setConnectionCallback(
                    std::bind(&ChatService::handleConnection, this, std::placeholders::_1));
            server_->setMessageCallback(
                    std::bind(&ChatService::handleMessage, this, std::placeholders::_1, std::placeholders::_2));
            server_->setCloseCallback(
                    std::bind(&ChatService::handleClose, this, std::placeholders::_1));

            // 启动服务器
            server_->start();

            isRunning_ = true;
            return true;
        }

// 停止服务
        void ChatService::stop() {
            if (!isRunning_) {
                return;
            }

            server_->stop();
            isRunning_ = false;
        }

// 处理新连接
        void ChatService::handleConnection(std::shared_ptr<network::Connection> conn) {
            // 记录连接信息，可以在这里做一些初始化工作
            LOG_INFO("新客户端连接: " + conn->getIp() + ":" + std::to_string(conn->getPort()));

            // 保存连接到连接映射表
            {
                std::lock_guard<std::mutex> lock(connectionsMutex_);
                connections_[conn->getId()] = conn;
            }
        }

// 处理客户端消息
        void ChatService::handleMessage(std::shared_ptr<network::Connection> conn, const std::string& message) {
            // 解析JSON消息
            nlohmann::json root;

            try {
                root = nlohmann::json::parse(message);
            } catch (const nlohmann::json::parse_error& e) {
                // 解析失败，返回错误信息
                nlohmann::json response;
                response["status"] = "error";
                response["message"] = "Invalid JSON format: " + std::string(e.what());
                conn->send(response.dump());
                return;
            }

            // 获取请求路径、方法和参数
            std::string path = root.value("path", "");
            std::string method = root.value("method", "GET");
            nlohmann::json params = root.value("params", nlohmann::json());

            // 处理请求
            std::string responseStr = handleRequest(path, method, params);
            conn->send(responseStr);
        }

// 处理连接关闭
        void ChatService::handleClose(std::shared_ptr<network::Connection> conn) {
            // 获取连接对应的用户ID
            int connId = conn->getId();

            // 从连接映射表中删除
            {
                std::lock_guard<std::mutex> lock(connectionsMutex_);
                connections_.erase(connId);
            }

            std::lock_guard<std::mutex> lock(connectionUsersMutex_);
            auto it = connectionUsers_.find(connId);
            if (it != connectionUsers_.end()) {
                int userId = it->second;

                // 从用户连接映射中删除
                {
                    std::lock_guard<std::mutex> userLock(userConnectionsMutex_);
                    userConnections_.erase(userId);
                }

                // 从连接用户映射中删除
                connectionUsers_.erase(connId);
            }
        }

// 处理API请求
        std::string ChatService::handleRequest(const std::string& path, const std::string& method,
                                               const nlohmann::json& params) {
            nlohmann::json response;

            try {
                // 验证token（除了登录/注册外的所有接口都需要验证token）
                std::string token = params.value("token", "");
                int userId = 0;

                if (path != "/api/chat/login" && !verifyToken(token, userId)) {
                    response["status"] = "error";
                    response["message"] = "Unauthorized";
                    return response.dump();
                }

                if (path == "/api/chat/login" && method == "POST") {
                    // 用户登录聊天服务
                    std::string token = params.value("token", "");
                    int connId = params.value("conn_id", 0);

                    if (!verifyToken(token, userId)) {
                        response["status"] = "error";
                        response["message"] = "Invalid token";
                    } else {
                        // 获取连接ID对应的Connection
                        std::shared_ptr<network::Connection> conn;

                        {
                            std::lock_guard<std::mutex> lock(connectionsMutex_);
                            auto it = connections_.find(connId);
                            if (it != connections_.end()) {
                                conn = it->second;
                            }
                        }

                        if (!conn) {
                            response["status"] = "error";
                            response["message"] = "Connection not found";
                        } else {
                            // 记录用户连接映射
                            {
                                std::lock_guard<std::mutex> lock(userConnectionsMutex_);
                                userConnections_[userId] = conn;
                            }

                            // 记录连接用户映射
                            {
                                std::lock_guard<std::mutex> lock(connectionUsersMutex_);
                                connectionUsers_[connId] = userId;
                            }

                            response["status"] = "success";
                            response["user_id"] = userId;
                        }
                    }
                } else if (path == "/api/chat/send_private" && method == "POST") {
                    // 发送私聊消息
                    ChatMessage message = ChatMessage::fromJson(params);
                    message.senderId = userId;
                    message.type = params.value("type", 0);

                    // 获取当前时间
                    std::time_t now = std::time(nullptr);
                    char timeStr[32];
                    std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
                    message.createdAt = timeStr;

                    int messageId = sendPrivateMessage(message);

                    if (messageId > 0) {
                        response["status"] = "success";
                        response["message_id"] = messageId;
                    } else {
                        response["status"] = "error";
                        response["message"] = "Failed to send message";
                    }
                } else if (path == "/api/chat/private_history" && method == "GET") {
                    // 获取私聊历史
                    int otherUserId = params.value("user_id", 0);
                    int limit = params.value("limit", 20);
                    int offset = params.value("offset", 0);

                    std::vector<ChatMessage> messages = getPrivateHistory(userId, otherUserId, limit, offset);

                    nlohmann::json messageArray = nlohmann::json::array();
                    for (const auto& msg : messages) {
                        messageArray.push_back(msg.toJson());
                    }

                    response["status"] = "success";
                    response["messages"] = messageArray;
                } else if (path == "/api/chat/send_room" && method == "POST") {
                    // 发送群聊消息
                    int roomId = params.value("room_id", 0);

                    ChatMessage message;
                    message.senderId = userId;
                    message.content = params.value("content", "");
                    message.type = params.value("type", 0);

                    // 获取当前时间
                    std::time_t now = std::time(nullptr);
                    char timeStr[32];
                    std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
                    message.createdAt = timeStr;

                    int messageId = sendRoomMessage(roomId, message);

                    if (messageId > 0) {
                        response["status"] = "success";
                        response["message_id"] = messageId;
                    } else {
                        response["status"] = "error";
                        response["message"] = "Failed to send message";
                    }
                } else if (path == "/api/chat/room_history" && method == "GET") {
                    // 获取群聊历史
                    int roomId = params.value("room_id", 0);
                    int limit = params.value("limit", 20);
                    int offset = params.value("offset", 0);

                    std::vector<ChatMessage> messages = getRoomHistory(roomId, limit, offset);

                    nlohmann::json messageArray = nlohmann::json::array();
                    for (const auto& msg : messages) {
                        messageArray.push_back(msg.toJson());
                    }

                    response["status"] = "success";
                    response["messages"] = messageArray;
                } else if (path == "/api/chat/create_room" && method == "POST") {
                    // 创建聊天室
                    ChatRoom room = ChatRoom::fromJson(params);
                    room.creatorId = userId;

                    // 获取当前时间
                    std::time_t now = std::time(nullptr);
                    char timeStr[32];
                    std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
                    room.createdAt = timeStr;

                    int roomId = createRoom(room);

                    if (roomId > 0) {
                        // 创建者自动加入聊天室
                        joinRoom(roomId, userId);

                        response["status"] = "success";
                        response["room_id"] = roomId;
                    } else {
                        response["status"] = "error";
                        response["message"] = "Failed to create room";
                    }
                } else if (path == "/api/chat/join_room" && method == "POST") {
                    // 加入聊天室
                    int roomId = params.value("room_id", 0);

                    if (joinRoom(roomId, userId)) {
                        response["status"] = "success";
                    } else {
                        response["status"] = "error";
                        response["message"] = "Failed to join room";
                    }
                } else if (path == "/api/chat/leave_room" && method == "POST") {
                    // 离开聊天室
                    int roomId = params.value("room_id", 0);

                    if (leaveRoom(roomId, userId)) {
                        response["status"] = "success";
                    } else {
                        response["status"] = "error";
                        response["message"] = "Failed to leave room";
                    }
                } else if (path == "/api/chat/user_rooms" && method == "GET") {
                    // 获取用户加入的聊天室
                    std::vector<ChatRoom> rooms = getUserRooms(userId);

                    nlohmann::json roomArray = nlohmann::json::array();
                    for (const auto& room : rooms) {
                        roomArray.push_back(room.toJson());
                    }

                    response["status"] = "success";
                    response["rooms"] = roomArray;
                } else if (path == "/api/chat/room_members" && method == "GET") {
                    // 获取聊天室成员
                    int roomId = params.value("room_id", 0);

                    std::vector<int> members = getRoomMembers(roomId);

                    nlohmann::json memberArray = nlohmann::json::array();
                    for (const auto& memberId : members) {
                        memberArray.push_back(memberId);
                    }

                    response["status"] = "success";
                    response["members"] = memberArray;
                } else if (path == "/api/chat/mark_read" && method == "POST") {
                    // 标记消息为已读
                    int messageId = params.value("message_id", 0);

                    if (markAsRead(messageId)) {
                        response["status"] = "success";
                    } else {
                        response["status"] = "error";
                        response["message"] = "Failed to mark message as read";
                    }
                } else if (path == "/api/chat/unread_count" && method == "GET") {
                    // 获取未读消息数
                    int count = getUnreadCount(userId);

                    response["status"] = "success";
                    response["count"] = count;
                } else {
                    response["status"] = "error";
                    response["message"] = "Unknown API path";
                }
            } catch (const std::exception& e) {
                response["status"] = "error";
                response["message"] = std::string("Server error: ") + e.what();
            }

            return response.dump();
        }

// 发送私聊消息
        int ChatService::sendPrivateMessage(const ChatMessage& message) {
            // 获取当前时间
            std::time_t now = std::time(nullptr);
            char timeStr[32];
            std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
            std::string createdAt = timeStr;

            int messageId = 0;

            try {
                // 插入消息记录
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return 0;
                }

                // 使用简单的字符串转义函数
                auto escapeString = [](const std::string& str) -> std::string {
                    std::string result;
                    result.reserve(str.size() * 2);
                    for (char c : str) {
                        if (c == '\'') {
                            result += "''";
                        } else if (c == '\\') {
                            result += "\\\\";
                        } else {
                            result += c;
                        }
                    }
                    return result;
                };

                std::string query = "INSERT INTO chat_messages (sender_id, receiver_id, content, created_at, type, status) "
                                    "VALUES (" + std::to_string(message.senderId) + ", " +
                                    std::to_string(message.receiverId) + ", '" +
                                    escapeString(message.content) + "', '" +
                                    createdAt + "', " +
                                    std::to_string(message.type) + ", 0)";

                if (!conn->query(query)) {
                    return 0;
                }

                // 获取消息ID
                messageId = conn->getInsertId();

                // 向接收者发送消息
                if (messageId > 0) {
                    ChatMessage newMessage = message;
                    newMessage.id = messageId;
                    newMessage.createdAt = createdAt;
                    newMessage.status = 0;  // 未读

                    // 将消息转换为JSON
                    nlohmann::json jsonMessage;
                    jsonMessage["type"] = "private_message";
                    jsonMessage["message"] = newMessage.toJson();

                    std::string jsonStr = jsonMessage.dump();

                    // 向接收者发送消息
                    sendToUser(message.receiverId, jsonStr);
                }
            } catch (const std::exception& e) {
                // 处理异常
            }

            return messageId;
        }

// 发送群聊消息
        int ChatService::sendRoomMessage(int roomId, const ChatMessage& message) {
            // 获取当前时间
            std::time_t now = std::time(nullptr);
            char timeStr[32];
            std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
            std::string createdAt = timeStr;

            int messageId = 0;

            try {
                // 插入消息记录
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return 0;
                }

                // 使用简单的字符串转义函数
                auto escapeString = [](const std::string& str) -> std::string {
                    std::string result;
                    result.reserve(str.size() * 2);
                    for (char c : str) {
                        if (c == '\'') {
                            result += "''";
                        } else if (c == '\\') {
                            result += "\\\\";
                        } else {
                            result += c;
                        }
                    }
                    return result;
                };

                std::string query = "INSERT INTO chat_room_messages (room_id, sender_id, content, created_at, type) "
                                    "VALUES (" + std::to_string(roomId) + ", " +
                                    std::to_string(message.senderId) + ", '" +
                                    escapeString(message.content) + "', '" +
                                    createdAt + "', " +
                                    std::to_string(message.type) + ")";

                if (!conn->query(query)) {
                    return 0;
                }

                // 获取消息ID
                messageId = conn->getInsertId();

                // 向聊天室所有成员发送消息
                if (messageId > 0) {
                    ChatMessage newMessage = message;
                    newMessage.id = messageId;
                    newMessage.createdAt = createdAt;

                    // 将消息转换为JSON
                    nlohmann::json jsonMessage;
                    jsonMessage["type"] = "room_message";
                    jsonMessage["room_id"] = roomId;
                    jsonMessage["message"] = newMessage.toJson();

                    std::string jsonStr = jsonMessage.dump();

                    // 向聊天室所有成员发送消息
                    sendToRoom(roomId, jsonStr);
                }
            } catch (const std::exception& e) {
                // 处理异常
            }

            return messageId;
        }

// 获取私聊消息历史
        std::vector<ChatMessage> ChatService::getPrivateHistory(int senderId, int receiverId, int limit, int offset) {
            std::vector<ChatMessage> messages;

            try {
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return messages;
                }

                std::string query = "SELECT * FROM chat_messages "
                                    "WHERE (sender_id = " + std::to_string(senderId) + " AND receiver_id = " + std::to_string(receiverId) + ") "
                                                                                                                                            "OR (sender_id = " + std::to_string(receiverId) + " AND receiver_id = " + std::to_string(senderId) + ") "
                                                                                                                                                                                                                                                 "ORDER BY created_at DESC LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);

                if (!conn->query(query)) {
                    return messages;
                }

                MYSQL_RES* result = conn->getResult();
                if (!result) {
                    return messages;
                }

                MYSQL_ROW row;
                while ((row = mysql_fetch_row(result))) {
                    ChatMessage message;
                    message.id = std::stoi(row[0]);
                    message.senderId = std::stoi(row[1]);
                    message.receiverId = std::stoi(row[2]);
                    message.content = row[3] ? row[3] : "";
                    message.createdAt = row[4] ? row[4] : "";
                    message.type = row[5] ? std::stoi(row[5]) : 0;
                    message.status = row[6] ? std::stoi(row[6]) : 0;

                    messages.push_back(message);
                }

                mysql_free_result(result);
            } catch (const std::exception& e) {
                // 处理异常
            }

            return messages;
        }

// 获取群聊消息历史
        std::vector<ChatMessage> ChatService::getRoomHistory(int roomId, int limit, int offset) {
            std::vector<ChatMessage> messages;

            try {
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return messages;
                }

                std::string query = "SELECT * FROM chat_room_messages "
                                    "WHERE room_id = " + std::to_string(roomId) +
                                    " ORDER BY created_at DESC LIMIT " + std::to_string(limit) +
                                    " OFFSET " + std::to_string(offset);

                if (!conn->query(query)) {
                    return messages;
                }

                MYSQL_RES* result = conn->getResult();
                if (!result) {
                    return messages;
                }

                MYSQL_ROW row;
                while ((row = mysql_fetch_row(result))) {
                    ChatMessage message;
                    message.id = std::stoi(row[0]);
                    message.senderId = std::stoi(row[2]);  // room_id is row[1]
                    message.content = row[3] ? row[3] : "";
                    message.createdAt = row[4] ? row[4] : "";
                    message.type = row[5] ? std::stoi(row[5]) : 0;

                    messages.push_back(message);
                }

                mysql_free_result(result);
            } catch (const std::exception& e) {
                // 处理异常
            }

            return messages;
        }

// 创建聊天室
        int ChatService::createRoom(const ChatRoom& room) {
            // 获取当前时间
            std::time_t now = std::time(nullptr);
            char timeStr[32];
            std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
            std::string createdAt = timeStr;

            int roomId = 0;

            try {
                // 插入聊天室记录
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return 0;
                }

                // 使用简单的字符串转义函数
                auto escapeString = [](const std::string& str) -> std::string {
                    std::string result;
                    result.reserve(str.size() * 2);
                    for (char c : str) {
                        if (c == '\'') {
                            result += "''";
                        } else if (c == '\\') {
                            result += "\\\\";
                        } else {
                            result += c;
                        }
                    }
                    return result;
                };

                std::string query = "INSERT INTO chat_rooms (name, description, creator_id, created_at, type) "
                                    "VALUES ('" + escapeString(room.name) + "', '" +
                                    escapeString(room.description) + "', " +
                                    std::to_string(room.creatorId) + ", '" +
                                    createdAt + "', " +
                                    std::to_string(room.type) + ")";

                if (!conn->query(query)) {
                    return 0;
                }

                // 获取聊天室ID
                roomId = conn->getInsertId();

                // 将创建者加入聊天室
                if (roomId > 0) {
                    joinRoom(roomId, room.creatorId);
                }
            } catch (const std::exception& e) {
                // 处理异常
            }

            return roomId;
        }

// 加入聊天室
        bool ChatService::joinRoom(int roomId, int userId) {
            bool success = false;

            try {
                // 检查用户是否已经在聊天室中
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return false;
                }

                std::string query = "SELECT * FROM chat_room_members "
                                    "WHERE room_id = " + std::to_string(roomId) +
                                    " AND user_id = " + std::to_string(userId);

                if (!conn->query(query)) {
                    return false;
                }

                MYSQL_RES* result = conn->getResult();
                if (!result) {
                    return false;
                }

                if (mysql_num_rows(result) > 0) {
                    // 用户已经在聊天室中
                    mysql_free_result(result);
                    return true;
                }

                mysql_free_result(result);

                // 加入聊天室
                query = "INSERT INTO chat_room_members (room_id, user_id, joined_at) "
                        "VALUES (" + std::to_string(roomId) + ", " +
                        std::to_string(userId) + ", NOW())";

                if (!conn->query(query)) {
                    return false;
                }

                // 更新内存中的聊天室成员映射
                {
                    std::lock_guard<std::mutex> lock(roomMembersMutex_);
                    roomMembers_[roomId].push_back(userId);
                }

                success = true;
            } catch (const std::exception& e) {
                // 处理异常
            }

            return success;
        }

// 离开聊天室
        bool ChatService::leaveRoom(int roomId, int userId) {
            bool success = false;

            try {
                // 从聊天室成员表中删除记录
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return false;
                }

                std::string query = "DELETE FROM chat_room_members "
                                    "WHERE room_id = " + std::to_string(roomId) +
                                    " AND user_id = " + std::to_string(userId);

                if (!conn->query(query)) {
                    return false;
                }

                // 更新内存中的聊天室成员映射
                {
                    std::lock_guard<std::mutex> lock(roomMembersMutex_);
                    auto it = roomMembers_.find(roomId);
                    if (it != roomMembers_.end()) {
                        auto& members = it->second;
                        members.erase(std::remove(members.begin(), members.end(), userId), members.end());
                    }
                }

                success = true;
            } catch (const std::exception& e) {
                // 处理异常
            }

            return success;
        }

// 获取用户加入的聊天室
        std::vector<ChatRoom> ChatService::getUserRooms(int userId) {
            std::vector<ChatRoom> rooms;

            try {
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return rooms;
                }

                std::string query = "SELECT r.* FROM chat_rooms r "
                                    "JOIN chat_room_members m ON r.id = m.room_id "
                                    "WHERE m.user_id = " + std::to_string(userId);

                if (!conn->query(query)) {
                    return rooms;
                }

                MYSQL_RES* result = conn->getResult();
                if (!result) {
                    return rooms;
                }

                MYSQL_ROW row;
                while ((row = mysql_fetch_row(result))) {
                    ChatRoom room;
                    room.id = std::stoi(row[0]);
                    room.name = row[1] ? row[1] : "";
                    room.description = row[2] ? row[2] : "";
                    room.creatorId = std::stoi(row[3]);
                    room.createdAt = row[4] ? row[4] : "";
                    room.type = row[5] ? std::stoi(row[5]) : 0;

                    rooms.push_back(room);
                }

                mysql_free_result(result);
            } catch (const std::exception& e) {
                // 处理异常
            }

            return rooms;
        }

// 获取聊天室成员
        std::vector<int> ChatService::getRoomMembers(int roomId) {
            std::vector<int> members;

            // 先查找内存中的缓存
            {
                std::lock_guard<std::mutex> lock(roomMembersMutex_);
                auto it = roomMembers_.find(roomId);
                if (it != roomMembers_.end()) {
                    return it->second;
                }
            }

            try {
                // 从数据库加载
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return members;
                }

                std::string query = "SELECT user_id FROM chat_room_members "
                                    "WHERE room_id = " + std::to_string(roomId);

                if (!conn->query(query)) {
                    return members;
                }

                MYSQL_RES* result = conn->getResult();
                if (!result) {
                    return members;
                }

                MYSQL_ROW row;
                while ((row = mysql_fetch_row(result))) {
                    members.push_back(std::stoi(row[0]));
                }

                mysql_free_result(result);

                // 更新内存缓存
                {
                    std::lock_guard<std::mutex> lock(roomMembersMutex_);
                    roomMembers_[roomId] = members;
                }
            } catch (const std::exception& e) {
                // 处理异常
            }

            return members;
        }

// 标记消息为已读
        bool ChatService::markAsRead(int messageId) {
            bool success = false;

            try {
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return false;
                }

                std::string query = "UPDATE chat_messages SET status = 1 "
                                    "WHERE id = " + std::to_string(messageId);

                if (!conn->query(query)) {
                    return false;
                }

                success = (conn->getAffectedRows() > 0);
            } catch (const std::exception& e) {
                // 处理异常
            }

            return success;
        }

// 获取未读消息数
        int ChatService::getUnreadCount(int userId) {
            int count = 0;

            try {
                auto conn = dbPool_->getConnection();
                if (!conn) {
                    return 0;
                }

                std::string query = "SELECT COUNT(*) FROM chat_messages "
                                    "WHERE receiver_id = " + std::to_string(userId) +
                                    " AND status = 0";

                if (!conn->query(query)) {
                    return 0;
                }

                MYSQL_RES* result = conn->getResult();
                if (!result) {
                    return 0;
                }

                MYSQL_ROW row = mysql_fetch_row(result);
                if (row && row[0]) {
                    count = std::stoi(row[0]);
                }

                mysql_free_result(result);
            } catch (const std::exception& e) {
                // 处理异常
            }

            return count;
        }

// 向指定用户发送消息
        void ChatService::sendToUser(int userId, const std::string& message) {
            std::lock_guard<std::mutex> lock(userConnectionsMutex_);
            auto it = userConnections_.find(userId);
            if (it != userConnections_.end() && it->second) {
                it->second->send(message);
            }
        }

// 向聊天室所有成员发送消息
        void ChatService::sendToRoom(int roomId, const std::string& message) {
            // 获取聊天室成员
            std::vector<int> members = getRoomMembers(roomId);

            // 向所有成员发送消息
            for (int memberId : members) {
                sendToUser(memberId, message);
            }
        }

// 验证token
        bool ChatService::verifyToken(const std::string& token, int& userId) {
            if (token.empty()) {
                return false;
            }

            try {
                // 从Redis中获取token对应的用户ID
                std::string redisKey = "token:" + token;
                std::string value = redisClient_->get(redisKey);

                if (value.empty()) {
                    return false;
                }

                // 解析用户ID
                try {
                    userId = std::stoi(value);
                    return true;
                } catch (const std::exception& e) {
                    return false;
                }
            } catch (const std::exception& e) {
                return false;
            }
        }

    } // namespace chat
} // namespace service 